package com.matt.sooncleaner.junk

import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.Utils
import com.cloud.cleanjunksdk.task.CheckSdkCallback
import com.cloud.cleanjunksdk.task.Clean
import com.cloud.cleanjunksdk.task.CleanSDK
import com.cloud.cleanjunksdk.tools.Region
import com.cloud.cleanjunksdk.tools.Utils as CleanUtils


object CleanManager {
    private var isInitSuccess = false
    private var sdkClean: Clean? = null

    fun initCleanSDK() {
        CleanSDK.init(
            Utils.getApp(),
            Utils.getApp().applicationContext,
            Region.INTL,
            object : CheckSdkCallback {
                override fun onSuccess(clean: Clean) {
                    isInitSuccess = true
//                    Log.d(TAG, "################initCleanSDK onSuccess ")
                    sdkClean = clean
                    sdkClean?.timeout(20000)
                }

                override fun onError(errCode: Int) {
                    isInitSuccess = false
                    ToastUtils.showLong("Initialization failed with error $errCode")
                }
            }) //initialize SDK
    }

    fun isInitSuccess() = isInitSuccess

    private fun getAllApp(): List<String> {
        val pm: PackageManager = Utils.getApp().packageManager
        val installedPackages = pm.getInstalledApplications(PackageManager.GET_META_DATA)
        return installedPackages.map { it.packageName }
    }

    fun requestPermission(activity: Activity) =
        CleanUtils.requestForPermission(Utils.getApp(), activity)

    fun canUseCleanJunk() = CleanUtils.canAccessExternalSd(Utils.getApp()) && isInitSuccess

    fun handleActivityResult(requestCode: Int, data: Intent): Boolean {
        val sdkClean = sdkClean?:return false
        if (requestCode == sdkClean.requestCode && sdkClean.updateAndroidDataPermission(requestCode, data)) {
            return true
        } else {
            return false
        }
    }

    fun requestAndroidDataPermission(activity: Activity): Boolean {
        if (Build.VERSION.SDK_INT >= 32) {
            val pm: PackageManager = Utils.getApp().packageManager
            val installedPackages = pm.getInstalledApplications(PackageManager.GET_META_DATA)
            val allPackages = installedPackages.map { it.packageName }
            sdkClean?.requestAndroidDataPermission(activity, allPackages)
            return true
        } else if (Build.VERSION.SDK_INT >= 30 && Build.VERSION.SDK_INT < 32) {
            sdkClean?.requestAndroidDataPermission(activity, mutableListOf())
            return true
        } else {
            return false
        }
    }

    fun getCleanSdk() = sdkClean
}